package com.jinsp.webviewservice;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;

import com.jinsp.webviewservice.webview.WebViewConfig;

public final class WebViewActivity extends AppCompatActivity implements IFragment2ActivityCallback {

    private TextView titleTextView;
    private WebViewFragment webViewFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        setContentView(R.layout.activity_webview);
        WebViewConfig webViewConfig = getIntent().getParcelableExtra(WebViewConfig.TAG);
        if (webViewConfig == null) {
            finish();
        } else {
            Toolbar toolbar = findViewById(R.id.tool_bar_web_view);
            toolbar.setTitle("");
            setSupportActionBar(toolbar);
            webViewFragment = WebViewFragment.newInstance(webViewConfig);
            if (!webViewConfig.isShowTitleBar()) {
                toolbar.setVisibility(View.GONE);
            } else {
                toolbar.setBackgroundColor(webViewConfig.getTitleBackground());
                titleTextView = toolbar.findViewById(R.id.tv_web_view_title);
                titleTextView.setTextColor(webViewConfig.getTitleTextColor());
                titleTextView.setText(webViewConfig.getTitleName());
                ImageButton webViewBackImageButton = toolbar.findViewById(R.id.ib_web_view_back);
                if (webViewConfig.getBackDrawableId() != 0) {
                    webViewBackImageButton.setImageDrawable(getResources().getDrawable(webViewConfig.getBackDrawableId()));
                    webViewBackImageButton.setOnClickListener(v -> onBackPressed());
                }
            }
            webViewFragment.setFragment2ActivityCallback(this);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.web_view_fragment, webViewFragment,
                            WebViewFragment.TAG)
                    .commit();
        }
    }

    @Override
    public void updateTitleText(String title) {
        if (titleTextView != null) {
            titleTextView.setText(title);
        }
    }

    @Override
    public void onBackPressed() {
        if (!webViewFragment.back()) {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //停止进程
        System.exit(0);
    }
}